<?php

namespace app\admin\controller\newhouse\customer;

use app\common\controller\Backend;
use think\Db;

/**
 * 客户跟进
 *
 * @icon fa fa-circle-o
 */
class Follow extends Backend
{
    
    /**
     * Follow模型对象
     * @var \app\admin\model\newhouse\customer\Follow
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\newhouse\customer\Follow;
        $this->view->assign("stateList", $this->model->getStateList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $where1='1=1';
            $group = $this->auth->getGroups()[0];
            $group_name=$group['name'];
            if($group_name=='楼盘代理商' || $group_name=='楼盘开发商'){
                $where1 .= ' and cop_id='. $this->auth->cop_id;
            }else if($group_name=='开发商案场负责人' || $group_name='代理商案场负责人'){
                $where1 .= ' and add_userid=' . $this->auth->id;
            }else if($group_name=='Admin group'){
                
            }else{
                $this->error(__('You have no permission'));
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['newhousecustomeritems','newhouseadmin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['newhousecustomeritems','newhouseadmin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('newhousecustomeritems')->visible(['customer_name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
    * 跟进状态
    */
    public function addstate($ids)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['create_userid']=$this->auth->id;
                    $params['create_time']=time();
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();

                    $customer_model = \app\admin\model\newhouse\customer\Items::get($params['customer_id']);
                    $customer_model->updatetime=time();
                    $customer_model->update_userid = $this->auth->id;
                    $customer_model->save();

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('跟进成功',null,[
                        'follow_content'=>$params['follow_content'],
                        'create_time'=>date("Y-m-d H:i:s",$this->model->create_time),
                        'create_user'=>$this->auth->nickname,
                        'state'=>$this->model->state
                    ]);
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $customer_model = \app\admin\model\newhouse\customer\Items::get($ids);
        $this->assign('state',$customer_model->state);
        $this->assign('customer_id',$ids);
        return $this->view->fetch();
    }
   
    /**
    * 添加手机号
    */
    public function addmobile($ids)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $customer_id = $ids;
            $mobile = $params['customer_mobile'];

            // 判重
            $customer_model_has = new  \app\admin\model\newhouse\customer\Items;
            $whereexists="customer_tel = '" . $mobile . "' OR customer_tel2='" . $mobile . "' OR customer_tel3='" . $mobile . "'";
            $has = $customer_model_has->where($whereexists)->count();
            if($has>0){
                $this->error('号码已经存在');
                return;
            }

            $customer_model = \app\admin\model\newhouse\customer\Items::get($customer_id);
            if($customer_model->customer_tel==$mobile){
                $this->error('号码没有变化');
                return;
            }
            if(empty($customer_model->customer_tel2)){
                $customer_model->customer_tel2 = $mobile;
            }else if(empty($customer_model->customer_tel3)){
                if($customer_model->customer_tel2==$mobile){
                    $this->error('号码没有变化');
                    return;
                }
                $customer_model->customer_tel3=$mobile;
            }else{
                $this->error('无法录入更多号码');
                return;
            }
            $customer_model->save();
            
            // 新增记录
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['create_userid']=$this->auth->id;
                    $params['create_time']=time();
                    $params['state']='跟进号码' ;
                    $params['follow_content']= substr_replace($mobile,'****',3,4);
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                    $this->success("新增客户号码操作成功",null,['mobile'=>$mobile]);
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                
            }
            $this->error(__('Parameter %s can not be empty', ''));

           
        }
        $this->assign('customer_id',$ids);
        return $this->view->fetch();
    }
}
